// import router from './router/index.js'
import store from './store/index.js'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import router from '@/router/index.js'
const whileList = ['/404', '/login']
router.beforeEach(async(to, from, next) => {
  nprogress.start()
  //   判断是否登录
  if (store.getters.token) {
    if (!store.getters.userId) {
      // { constantRoutes,  }
      // await store.dispatch('user/getUserInfo')
      // const { roles: { menus }} = await store.dispatch('user/getUserInfo')
      // console.log('menus', menus)
      // //       // 过滤动态路由
      // const filterRouters = asyncRoutes.filter(t => menus.includes(t.name))
      // //       // 添加动态路由
      // router.addRoutes([...filterRouters, { path: '*', redirect: '/404', hidden: true }])
      // //       // 解决菜单没变化的问题
      // router.options.routes = [...constantRoutes, ...filterRouters]
      // // 解决404问题
      // // console.log('to.path', to.path)
      // return next(to.path)
      // 标准版写法
      // 1、获取菜单控制的标识
      const { roles: { menus }} = await store.dispatch('user/getUserInfo')
      console.log('menus', menus)
      // 2、过滤动态路由
      const filterRouters = await store.dispatch('permission/filterRoutes', menus)
      // const filterRouters = asyncRoutes.filter(t => menus.includes(t.name))
      //  3、添加动态路由
      router.addRoutes([...filterRouters, { path: '*', redirect: '/404', hidden: true }])
      // 4、解决404问题
      return next(to.path)
    }
    // if (!store.getters.userId) {
    //   // 1.获取菜单控制的标识
    //   const { roles: { menus }} = await store.dispatch('user/getUserInfo')
    //   console.log('menus', menus)
    //   // 2.过滤动态路由
    //   const filterRouters = asyncRoutes.filter(t => menus.includes(t.name))
    //   // 3.添加动态路由
    //   // 注意:addRoutes不会影响初始化路由配置,也就是说,router.option.routes不会跟着变
    //   router.addRoutes([...filterRouters, { path: '*', redirect: '/404', hidden: true }])
    //   // 4.解决菜单没变化的问题
    //   router.options.routes = [...constantRoutes, ...filterRouters]
    //   // 5.解决404问题
    //   return next(to.path)// 重新跳转一次
    // }
    // 是否去登录页面
    if (to.path === '/login') {
      return next('/')
    } else {
      next()
    }
  } else {
    //   是否为白名单
    if (whileList.includes(to.path)) {
      return next()
    }
    next('/login')
  }
  nprogress.done()
})
router.afterEach(() => {
  nprogress.done()
})
